package net.hmr_radio.hmrbot.controller.twitter;

import net.hmr_radio.hmrbot.controller.BaseController;
import net.hmr_radio.hmrbot.util.AssertionUtil;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.slim3.controller.Navigation;
import org.slim3.util.RequestUtil;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.RequestToken;

public class AuthController extends BaseController {

    private Log log = LogFactory.getLog(AuthController.class);

    @Override
    public Navigation run() throws Exception {
        AssertionUtil.nullCheck(sessionScope("destinationURL"));

        removeSessionScope("accessToken");
        removeSessionScope("accessTokenSecret");

        Twitter twitter = new TwitterFactory().getInstance();
        sessionScope("twitter", twitter);

        String callbackUrl = createCallbackUrl();
        log.info("callback url = " + callbackUrl);

        RequestToken requestToken = null;
        try {
            requestToken = twitter.getOAuthRequestToken(callbackUrl);
            sessionScope("requestToken", requestToken);
        } catch (TwitterException e) {
            return forward((String) sessionScope("destinationURL"));
        }

        String redirectUrl = requestToken.getAuthenticationURL();
        log.info("redirect url = " + redirectUrl);

        return redirect(redirectUrl);
    }

    private String createCallbackUrl() {
        String path = RequestUtil.getPath(request);
        String contextUrl =
            request.getRequestURL().substring(
                0,
                request.getRequestURL().lastIndexOf(path));
        return contextUrl + "/twitter/callback";
    }
}
